<template>
    <view>
      <view :style="objColor">
            <view class="sticky-header">
                <view v-if="isLgxny()" class="flex-alert">开票提醒，工作日09:00后正常开票</view>
                <view class="nav">
                    <view class="navs" @tap="yikai" data-skeleton-hide="hideHeader" v-if="hideHeader">
                        <view :class="show ? 'bigsize' : ''">
                            <template v-if="sellerNo=='tjhz'">
                                开票有效期30天
                            </template>
                            <template v-else>
                                未开发票
                            </template>
                            
                        </view>
                        <image src="https://oos-cn.ctyunapi.cn/front-end/static/mine/images/checkbox.png" :class="'img img1 ' + (show ? 'show' : 'hide')"></image>
                    </view>
                    <view class="navs" @tap="weikai" data-skeleton-hide="hideHeader" v-if="hideHeader">
                        <view :class="!show ? 'bigsize' : ''">发票记录</view>
                        <image src="https://oos-cn.ctyunapi.cn/front-end/static/mine/images/checkbox.png" :class="'img img2 ' + (!show ? 'show' : 'hide')"></image>
                    </view>
                </view>
            </view>

            <view class="conter" data-skeleton-hide="hideConter" v-if="hideConter">
                <!-- 未开发票 -->
                <view v-if="tabIndex == 1" style="padding-bottom: 120rpx">
                    <view v-if="list.length" class="conter-in">
                        <view class="list">
                            <!-- <van-checkbox-group value="{{ result }}" bind:change="onChange">
                        <van-cell-group> -->
                            <!-- <van-cell wx:for="{{ list }}" wx:key="index" value-class="value-class" clickable data-index="{{ index }}"> -->
                            <!-- <van-checkbox catch:tap="noop" class="checkboxes-{{ index }}" name="{{ item.id }}" data-id="{{item.id}}" value="{{ singleChecked }}" data-price="{{(item.actualPowerBalance+item.actualServiceBalance)}}" data-index="{{index}}" data-chose="{{ checked ? true : false }}" style="float: left;width: 10%;margin-top: 30rpx;" data-value="{{ result }}" /> -->

                            <view class="list-conter" @tap="check" :data-index="index" v-for="(item, index) in list" :key="index">
                                <view class="list-conter-left">
                                    <image :src="item.check ? (sellerNo=='jw'?'https://oos-cn.ctyunapi.cn/front-end/static/mine/images/checkbox_sel-blue.png':'https://oos-cn.ctyunapi.cn/front-end/static/mine/images/checkRefund_sel.png') : 'https://oos-cn.ctyunapi.cn/front-end/static/mine/images/checkRefund.png'" class="img1"></image>
                                    <view>
                                        <view class="left-name" :class="{ greyText: item.isOver }">订单号：{{ item.busId }}</view>
                                        <view class="left-time" :class="{ greyText: item.isOver }">下单时间：{{ item.createTime }}</view>
                                    </view>
                                </view>

                                <view class="list-conter-right" :class="{ greyText: item.isOver }">￥{{ (item.actualPowerBalance + item.actualServiceBalance) / 100 }}</view>
                            </view>
                            <!-- </van-cell> -->
                            <!-- </van-cell-group>
                    </van-checkbox-group> -->
                            <view class="bttom">
                                <view class="all-btn">
                                    <!-- <van-checkbox value="{{ checked }}" bind:change="onChanges" data-value="{{ result }}">本页全选</van-checkbox> -->
                                    <image :src="allCheck ? sellerNo=='jw'?'https://oos-cn.ctyunapi.cn/front-end/static/mine/images/checkbox_sel-blue.png':'https://oos-cn.ctyunapi.cn/front-end/static/mine/images/checkRefund_sel.png' : 'https://oos-cn.ctyunapi.cn/front-end/static/mine/images/checkRefund.png'" class="img" @tap="checkAll"></image>
                                    本页全选
                                </view>
                                <view class="all-prices">
                                    已选择：
                                    <span>{{ sumPrice / 100 }}元</span>
                                </view>
                                <view class="next-btn">
                                    <view @tap="invoiceDetails">下一步</view>
                                </view>
                            </view>
                        </view>
                        <view v-if="loadAll" class="noList">{{ tips }}</view>
                    </view>
                    <view v-if="list.length<=0&&loadingInvoice">
                        <Upgrading text="您暂无可开票订单~"></Upgrading>
                        <view class="goCharing" @tap="goCharing">去充电</view>
                    </view>
                </view>
                <!-- 已开发票 -->
                <view v-if="tabIndex == 2" style="padding-bottom: 120rpx">
                    <view v-if="recordLists.length > 0">
                        <view class="invoiced-record" :data-index="index" @tap="einvoiceDetails" :data-id="item.id" v-for="(item, index) in recordLists" :key="index">
                            <view class="record-in">
                                <view>{{ item.recordsCreateTime }}</view>
                                <image src="https://oos-cn.ctyunapi.cn/front-end/static/mine/images/turn.png"></image>
                            </view>

                            <view class="record-in">
                                <view>充电费用</view>
                                <view class="prices">￥{{ item.actualBalance / 100 }}</view>
                            </view>

                            <view class="aaa" v-if="item.invoiceStatus == 'INVOICE_APPLYING'">审核中</view>
                            <view class="aaa" v-else-if="item.invoiceStatus == 'INVOICE_CHECK'">审核中</view>
                            <view class="aaa" v-else-if="item.invoiceStatus == 'IN_INVOICE'">审核中</view>
                            <view class="aaa" v-else-if="item.invoiceStatus == 'INVOICE_FAIL'">开票失败</view>
                            <view class="aaa" v-else-if="item.invoiceStatus == 'CANCEL_INVOICE'">已退票</view>
                            <view class="aaa" v-else-if="item.invoiceStatus == 'INVOICE_FINISH'">已开票</view>
                            <view class="aaa" v-else-if="item.invoiceStatus == 'INVOICE_REJECT'">已退票</view>
                            <view class="aaa" v-else-if="item.invoiceStatus == 'REDED'">已退票</view>
                            <view class="aaa" v-else-if="item.invoiceStatus == 'NO_INVOICE'">未开票</view>
                            <view class="aaa" v-else-if="item.invoiceStatus == 'RED_APPLYING'">审核中</view>
                            <view class="aaa" v-else-if="item.invoiceStatus == 'RED_CHECK'">审核中</view>
                            <view class="aaa" v-else-if="item.invoiceStatus == 'IN_RED'">审核中</view>
                            <view class="aaa" v-else-if="item.invoiceStatus == 'RED_FAIL'">冲红失败</view>
                            <view class="aaa" v-else-if="item.invoiceStatus == 'IN_THE_VOID'">作废中</view>
                            <view class="aaa" v-else-if="item.invoiceStatus == 'VOIDED'">已作废</view>
                            <view class="aaa" v-else-if="item.invoiceStatus == 'RED_REJECT'">驳回冲红</view>
                            <view class="aaa" v-else-if="item.invoiceStatus == 'TO_PUSH'">重新推送</view>
                            <view class="aaa" v-else-if="item.invoiceStatus == 'VOID_APPLYING'">申请作废</view>
                            <view class="aaa" v-else-if="item.invoiceStatus == 'RED_INVOICE'">审核中</view>
                        </view>
                        <view v-if="loadAll" class="noList">{{ tips }}</view>
                    </view>
                    <view v-else>
                        <Upgrading text="您暂无发票记录~"></Upgrading>
                        <!-- <view class="goCharing" bindtap="goCharing">去充电</view> -->
                    </view>
                </view>
            </view>
        </view>
    </view>
</template>

<script>
'use strict';
// import vanCheckbox from '@vant/weapp/checkbox/index';
// import vanCheckboxGroup from '@vant/weapp/checkbox-group/index';
import Upgrading from '../../../components/upgrading/upgrading';

// exports.__esModule = true;

var https_1 = require('./../../../api/https.js');
var app = getApp(); // mine/pages/invoice/invoice.ts

export default {
    components: {
        // vanCheckbox,
        // vanCheckboxGroup,
        Upgrading
    },
    data() {
        return {
            sellerNo :app.globalData.sellerNo,
            allCheck: false,
            show: true,
            loading: true,
            loadingInvoice:false,
            hideHeader: false,
            hideConter: false,
            list: [],
            result: [],
            checked: false,
            sumPrice: 0,
            chose: true,
            activeIcon: 'https://oos-cn.ctyunapi.cn/front-end/static/mine/images/sel.png',
            inactiveIcon: 'https://oos-cn.ctyunapi.cn/front-end/static/mine/images/sel1.png',
            recordLists: [],
            current: 1,
            pages: 1,
            alreadyPage: 1,
            alreadyPages: 1,
            tabIndex: 1,
            billIds: [],
            singleChecked: false,
            loadAll: false,
            tips: '',
            size: 0,
            hideList: ''
        };
    },
    onLoad: function () {
        // var pages = getCurrentPages();
        // var currPage = pages[pages.length - 1];
        // if(currPage.data) {
        //     this.tabIndex=currPage.data.tabIndex
        //     this.show= currPage.data.show
        // }
        const applyInvoiceSuccess = uni.getStorageSync('applyInvoiceSuccess')
        console.log(applyInvoiceSuccess)
        if(applyInvoiceSuccess) {
            const { show, tabIndex } = JSON.parse(applyInvoiceSuccess)
            this.setData({
                show,
                tabIndex
            })
        }

         uni.setStorageSync('applyInvoiceSuccess','')



    },
    onShow: function () {
        this.progressiveLoad();

        if (this.show) {
            this.getUnInvoiceBillList('replace');
        } else {
            this.queryInvoiceRecordList('replace');
        }
    },
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {
        this.sumPrice= 0
    },
    // 页面上拉触底事件的处理函数
    onReachBottom: function () {
        if (this.show) {
            if (this.current == this.pages) {
                // 到底
                this.loadAll= true,
                    this.tips='已加载全部！'
            } else {
                this.current= ++this.current,
                    this.size= 10
                this.getUnInvoiceBillList('');
            }
        } else {
            if (this.alreadyPage == this.alreadyPages) {
                // 到底
                this.loadAll= true,
                    this.tips= '已加载全部订单！'
            } else {
                this.alreadyPage= ++this.alreadyPage,
                    this.size=10
                this.queryInvoiceRecordList('');
            }
        }
    },
    methods: {
        /**
         * 组件的方法列表
         */
        disposableLoad: function () {
            var that = this;
            setTimeout(function () {
                that.loading=false,
                    that.hideConter= true,
                    that.hideHeader= true
            }, 1000);
        },

        // 渐进式加载数据，逐步隐藏 loading
        progressiveLoad: function () {
            var that = this;
            setTimeout(function () {
                that.loading= false
            }, 100);
            setTimeout(function () {
                that.hideConter= true
            }, 100);
            setTimeout(function () {
                that.hideHeader= true
            }, 100);
        },

        yikai: function () {
            this.show= true,
                this.loadAll= false,
                this.tabIndex=1,
                this.current=1,
                this.alreadyPage= 1
            this.getUnInvoiceBillList('replace');
        },

        weikai: function () {
            this.show= false,
                this.allCheck= false,
                this.sumPrice=0,
                this.billIds= [],
                this.loadAll= false,
                this.current= 1,
                this.alreadyPage= 1,
                this.tabIndex= 2
            this.queryInvoiceRecordList('replace');
        },

        //单击选择
        onChange: function (event) {
            var billIds = event.detail.map(Number);
            this.result= event.detail,
                this.billIds= billIds
        },

        //选择需要开发票
        check: function (e) {
            var that = this;
            var index = e.currentTarget.dataset.index;
            var list = this.list;
            var money = 0;
            var billIds = [];
            var sumPrice = this.sumPrice;
            list.forEach(function (e, i) {
                if (i == index) {
                    e.check = !e.check;
                }

                if (e.check == true) {
                    billIds.push(e.id);
                    money += parseFloat(e.actualPowerBalance + e.actualServiceBalance);
                    that.sumPrice= money,
                        that.allCheck= true,
                        that.billIds= billIds
                }
            });
            list.forEach(function (e1) {
                if (e1.check == false) {
                    that.sumPrice= money,
                        that.allCheck= false,
                        that.billIds= billIds
                }
            });
            this.list=list
        },

        noop: function (event) {
            var index = event.currentTarget.dataset.index;
            var chose = event.currentTarget.dataset.chose;
            var checkbox = this.$mp.page.selectComponent('.checkboxes-' + index);
            var sumPrice = this.sumPrice;
            var id = event.currentTarget.dataset.id;

            if (checkbox.data.value && !this.checked) {
                sumPrice = sumPrice + Number(event.currentTarget.dataset.price);
            } else {
                sumPrice = Number(Number(sumPrice - event.currentTarget.dataset.price).toFixed(2));
            }

            var checked;

            if (this.result.length) {
                checked = this.result.length == this.list.length;
            }

            this.sumPrice= sumPrice,
                this.checked=checked
        },

        //全选
        onChanges: function (event) {
            var that = this;
            var $list = this.list;
            var arr = [];
            var sumNum = 0;

            if (event.detail == true) {
                $list.map(function (item) {
                    sumNum = sumNum + Number(item.actualPowerBalance + item.actualServiceBalance);
                    arr.push(item.id);
                    that.result=arr,
                        that.sumPrice=sumNum,
                        that.singleChecked= true
                });
                var billIds = event.currentTarget.dataset.value.map(Number);
                this.billIds= billIds
            } else {
                arr = [];
                this.result= [],
                    this.sumPrice= 0,
                    this.singleChecked= false
            }

            this.checked= event.detail,
                this.chose= event.detail
        },

        //选择全部
        checkAll: function () {
            var list = this.list;
            var money = 0;
            var billIds = [];
            this.allCheck=!this.allCheck

            if (this.allCheck) {
                list.forEach(function (element) {
                    element.check = true;
                    money += parseFloat(element.actualPowerBalance + element.actualServiceBalance);
                    billIds.push(element.id);
                });
                this.billIds= billIds,
                    this.sumPrice= money,
                    this.list= list
            }

            if (!this.allCheck) {
                list.forEach(function (element) {
                    element.check = false;
                });
                this.billIds=[],
                    this.sumPrice= 0,
                    this.list= list
            }
        },

        // 时间超过30天
        over30() {
            const checkedList = this.list.filter(it=>this.billIds.includes(it.id))
            const overList = checkedList.filter(it=> it.isOver)
            const busIds = overList.map(it=>it.busId)
            console.log(this.billIds, checkedList,overList);

            if (overList.length) {
                uni.showModal({
                    title: '温馨提示',
                    content: `订单号为: ${busIds.join(', ')} 的订单已超过订单开票时间，请联系线下客服`,
                    showCancel: false,
                    confirmText: '知道了',
                    success: res => {
                        if (res.confirm) {
                            let money = 0
                            const set = new Set(this.billIds)
                            checkedList.forEach(item => {
                                item.check = !item.isOver;
                                item.isOver && set.delete(item.id)
                                if(!item.isOver){
                                    money += parseFloat(item.actualPowerBalance + item.actualServiceBalance);
                                }
                                
                            })
                            this.sumPrice = money
                            this.billIds = Array.from(set)

                        }
                    }
                })
            }

            return !!overList.length
        },

        //下一步
        invoiceDetails: function () {

            if (["tjhz"].includes(this.sellerNo) && this.over30()) return

            if (!this.billIds.length) {
                uni.showToast({
                    title: '请选择未开发票订单',
                    icon: 'none',
                    duration: 2000
                });
            } else {
                var billIds = JSON.stringify(this.billIds);
                var sumPrice = this.sumPrice;
                uni.navigateTo({
                    url: '../invoiceDetails/invoiceDetails?billIds=' + billIds + '&sumPrice=' + sumPrice
                });
                var data = this.list;
                data.forEach(function (element) {
                    element.check = false;
                });
                this.list= data,
                    this.sumPrice= 0,
                    this.billIds= [],
                    this.allCheck= false,
                    this.current= 1,
                    this.alreadyPage= 1
            }
        },

        // 详情
        einvoiceDetails: function (e) {
            var id = e.currentTarget.dataset.id;

            if (id) {
                uni.navigateTo({
                    url: '../einvoiceDetails/einvoiceDetails?id=' + id
                });
            }
        },

        getUnInvoiceBillList: function (type) {
            var that = this;
            var tmp = this;
            uni.showLoading({
					title: '加载中...',
					mask: true
				});
				that.loadingInvoice=false
            https_1
                .getUnInvoiceBillList({
                    current: tmp.current,
                    size: 10
                })
                .then(function (res) {
                    if (res.code == 0) {
                        var data = res.data.records;
                        data.forEach(function (e) {
                            e.check = false;
                        });
                        tmp.current=res.data.current,
                            tmp.pages=res.data.pages


                        const now = new Date().getTime()
                        data.forEach(item=>{
                            item.isOver = now - new Date(item.createTime.replace(' ','T')).getTime() > 30 * 24 * 60 * 60 * 1000
                        })
                        if (type === 'replace') {
                            that.list= data
                        } else {
                            that.list=that.list.concat(data)
                        }
                        console.log('list', that.list)
                    }
                    uni.hideLoading();
                    that.loadingInvoice=true
                })
                ['catch'](function (err) {});
        },

        queryInvoiceRecordList: function (type) {
            var that = this;
            var tmp = this;
            uni.showLoading({
					title: '加载中...',
					mask: true
				});
				that.loadingInvoice=false
            https_1
                .queryInvoiceRecordList({
                    page: tmp.alreadyPage,
                    pageSize: 10
                })
                .then(function (res) {
                    if (res.code == 0) {
                        tmp.alreadyPage= res.data.current,
                            tmp.alreadyPages= res.data.pages

                        if (type === 'replace') {
                            that.recordLists= res.data.InvoiceRecordList
                        } else {
                            that.recordLists= that.recordLists.concat(res.data.InvoiceRecordList)
                        }
                    }
                    uni.hideLoading();
                    that.loadingInvoice=true
                })
                ['catch'](function (err) {});
        },

        //去充电
        goCharing: function () {
            uni.redirectTo({
                url: '/packageFunctional/sitelist/sitelist'
            });
        }
    }
};
</script>
<style lang="less">
@import url('./invoice.less');
.sticky-header {
    position: sticky;
    top: 0;
    z-index: 999;
    .flex-alert {
        width: 100%;
        height: 80rpx;
        font-size: 28rpx;
        color: #f9ae3d;
        padding: 8rpx 24rpx;
        box-sizing: border-box;
        background-color: #fdf6ec;
        display: flex;
        align-items: center;
    }
}
</style>
